package com.gton.lpl.controller;

import com.gton.lpl.common.annotation.SkipTokenByJWT;
import com.gton.lpl.common.pojo.RedisKeys;
import com.gton.lpl.common.pojo.Resp;
import com.gton.lpl.entity.GpMenu;
import com.gton.lpl.service.GpMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @description: 首页菜单控制器
 * @author: GuoTong
 * @createTime: 2021-10-17 17:01
 * @since JDK 1.8 OR 11
 **/
@RestController
@RequestMapping("/menu")
@Api(tags = {"首页菜单控制器"})
public class IndexMenuController {
    //菜单业务类bean引入
    @Autowired
    private GpMenuService gpMenuService;


    @Autowired
    @Qualifier("redisTemplateByMySelf")
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/gradeByOneList", name = "获取菜单列表")
    @SkipTokenByJWT
    @ApiOperation(value = "获取级连菜单列表", notes = "分页list查询")
    public Resp getlist(@RequestParam("thisPage") int thisPage, @RequestParam("pageSize") int pageSize) {
        //分页参数不合法（查询页数小于 0 页，或者查询页的数据小于等于0）
        if (thisPage < 0 || pageSize <= 0) {
            return Resp.error("请求参数不合法");
        }
        //优先查询缓存
        Object menu = redisTemplate.opsForValue().get(RedisKeys.MENU_REDIS_KEY);
        if (menu != null) {
            return Resp.Ok(menu);
        }
        Resp<List<GpMenu>> resp = new Resp<>();
        //只查询查有效的获取菜单：自连接级联查询
        List<GpMenu> records = gpMenuService.selfBySelf();
        List<GpMenu> returnResp = new ArrayList<>();
        for (GpMenu record : records) {
            //判断是否为空，如果未上级为空，那么自己就是顶级菜单:自连接查询只返回顶级菜单就行了
            Long topMenuId = record.getTopMenuId();
            if (Objects.isNull(topMenuId)) {
                returnResp.add(record);
            }
        }
        resp.setData(returnResp);
        //redis刷新
        redisTemplate.opsForValue().set(RedisKeys.MENU_REDIS_KEY, returnResp);
        redisTemplate.expire(RedisKeys.MENU_REDIS_KEY, 10, TimeUnit.DAYS);
        return resp;

    }
}
